﻿using System.Collections.Generic;
using System.Linq;


using BLToolkit.DataAccess;
using BLToolkit.Data.Linq;
using BLToolkit.Mapping;

// Code nay anh viet o day, chu khong phai dung san dau nhe.
// Chi dung san cac truy van sql, ko can thu tuc thoi,  new DataContext().. :P
namespace Core
{
    [TableName("tblDangNhap")]
    public class NguoiDung
    {
        [PrimaryKey, Identity]
        [MapField("TaiKhoanID")]
        public int ID { get; set; }
        public string TenDangNhap { get; set; }
        public string MatKhau { get; set; }
        public string PhanQuyen { get; set; }

        public static IQueryable<NguoiDung> NguoiDungs
        {
            get
            {
                using (var db = new DataContext())
                {
                    return db.GetTable<NguoiDung>();
                }
            }
        }
        public static List<NguoiDung> All()
        {
            return NguoiDungs.ToList();
        }
        public static NguoiDung Single(int id)
        {
            return NguoiDungs.SingleOrDefault(x => x.ID == id);
        }
        public static int Add(NguoiDung entity)
        {
            using (var db = new DataContext())
            {
                var exists = db.GetTable<NguoiDung>().FirstOrDefault(x => x.TenDangNhap == entity.TenDangNhap);
                if (exists == null)
                {
                    object rs = db.InsertWithIdentity(entity);
                    return int.Parse(rs.ToString());
                }
                return -1;
            }
        }
        public static int Update(NguoiDung entity)
        {
            using (var db = new DataContext())
            {
                return db.Update(entity);
            }
        }
        public static int Delete(int id)
        {
            return NguoiDungs.Delete(x => x.ID == id);
        }

        public static NguoiDung Login(string tenDangNhap, string matKhau)
        {
            return NguoiDungs.SingleOrDefault(x => x.TenDangNhap == tenDangNhap && x.MatKhau == matKhau);
        }
    }
}
